package com.kapark.cloud.socket;

import com.kapark.cloud.context.AudioSender;
import com.xiaoleilu.hutool.log.Log;
import com.xiaoleilu.hutool.log.LogFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author: hyzhan
 * @date: 2019/6/14
 * @desc: TODO
 */
@Component
@ServerEndpoint("/websocket/{devId}")
public class AudioSocket {

    private static Log log = LogFactory.get(AudioSocket.class);
    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;
    //concurrent包的线程安全Set，用来存放每个客户端对应的 AudioSocket 对象。
    private static ConcurrentHashMap<Integer, AudioSocket> webSocketMap = new ConcurrentHashMap<>();

    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;

    //接收devId
    private int devId;

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("devId") int devId) {
        this.session = session;
        this.devId = devId;

        webSocketMap.put(devId, this);
        addOnlineCount();           //在线数加1
        log.info("有新窗口开始监听:" + devId + ",当前在线人数为" + getOnlineCount());
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketMap.remove(devId, this);  //从set中删除
        subOnlineCount();           //在线数减1
        log.info("有一连接关闭！当前在线人数为" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(byte[] message, Session session) {
        log.info("接受byte length: " + message.length);
        AudioSender.send2Intercom(devId, message);
    }


    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误");
        error.printStackTrace();
    }

    /**
     * 发自定义消息
     */
    public static void send2Client(int devId, byte[] data, int len) {
        AudioSocket audioSocket = webSocketMap.get(devId);
        if (audioSocket != null) {
            try {
                synchronized (audioSocket.session) {
                    audioSocket.session.getBasicRemote().sendBinary(ByteBuffer.wrap(data, 0, len));
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static synchronized int getOnlineCount() {
        return onlineCount;
    }

    private static synchronized void addOnlineCount() {
        AudioSocket.onlineCount++;
    }

    private static synchronized void subOnlineCount() {
        AudioSocket.onlineCount--;
    }
}